package ua.edu.nuos.jeetraining2012.cms.util.mail.course;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import ua.edu.nuos.jeetraining2012.cms.entity.StudentEntity;
import ua.edu.nuos.jeetraining2012.cms.service.exception.ServiceException;
import ua.edu.nuos.jeetraining2012.cms.util.LocaleWrapper;
import ua.edu.nuos.jeetraining2012.cms.util.mail.NotifyInstructor;

import java.io.IOException;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;

/**
 * Send notify to course instructors about Student enrollment to course.
 *
 * @author Victor N. Ganichev victor.ganichev@gmail.com
 * @version 1.0 Date: 01.07.13 Time: 21:21
 * @since 1.0
 */
public class StudentEnrolledToCourse extends NotifyInstructor {

    /** Define student approve link. */
    private String approveStudentLink;

    /** Define student approve link. */
    private String discardLink;

    /** Define student entity, to send profile data. */
    private StudentEntity studentEntity;

    /** Define logger */
    final private static Logger logger = org.slf4j.LoggerFactory.getLogger(StudentEnrolledToCourse.class);

    // Constructors
    public StudentEnrolledToCourse() {
        logger.debug("StudentEnrolledToCourse invocation.");
        i18n = LocaleWrapper.getBundle("course");
    }

    // Getters & Setters
    public void setApproveStudentLink(String approveStudentLink) {
        this.approveStudentLink = approveStudentLink;
    }

    public void setStudentEntity(StudentEntity studentEntity) {
        this.studentEntity = studentEntity;
    }

    public void setDiscardLink(String discardLink) {
        this.discardLink = discardLink;
    }

    @Override
    public String getSubject() {
        try {
            logger.debug("Defining email subject.");
            MessageFormat formatter = new MessageFormat("");
            formatter.setLocale(LocaleWrapper.getLocale());
            formatter.applyPattern(i18n.getString("notify_instructor_subject"));

            return formatter.format(new Object[] {
                    i18n.getString("notify_instructor_subject"),
                    student.getName(),
                    course.getTitle()
            });

        } catch (MissingResourceException | NullPointerException e) {
            return "Інформація. Новий користувач записався на курс.";
        }
    }

    @Override
    public String getBodyMessage() {
        Map<String, Object> dataMap = new HashMap<>();
        String md5, approveURL, discardURL;

        MessageFormat formatter = new MessageFormat("");
        formatter.setLocale(LocaleWrapper.getLocale());
        formatter.applyPattern(i18n.getString("notify_instructor_body"));

        logger.debug("Forming notification mail about user {} enrollment to course {}", student.getId(), course.getId());
        try {
            md5 = courseService.getStudentToCourseApproveMd5(student.getId(), course.getId());
            approveURL = String.format("%s?id=%s", this.approveStudentLink, URLEncoder.encode(md5, "UTF-8"));
            discardURL = String.format("%s?id=%s", this.discardLink, URLEncoder.encode(md5, "UTF-8"));

            dataMap.put("noticeBody", formatter.format(new Object[] {
                    i18n.getString("notify_instructor_body"),
                    student.getName(),
                    course.getTitle(),
                    studentEntity.getBirthday(),
                    studentEntity.getPhone(),
                    student.getEmail(),
                    studentEntity.getSkype(),
                    studentEntity.getEducation(),
                    studentEntity.getOccupation(),
                    String.format("<a href=\"%1$s\">%1$s</a>", approveURL),
                    String.format("<a href=\"%1$s\">%1$s</a>", discardURL)
            }));

            Configuration cfg = getTemplateConfig();
            Template template = cfg.getTemplate("notifyInstructorStudentEnrolled.ftl");
            StringWriter writer = new StringWriter();
            template.process(dataMap, writer);
            return writer.toString();
        } catch (IOException | TemplateException |
                MissingResourceException | NullPointerException | ServiceException e) {
            logger.error("getBodyMessage() Exception", e);
        }
        return null;
    }
}
